package com.lee.ssm.service.impl;

import com.lee.ssm.dao.IUserDao;
import com.lee.ssm.domain.Role;
import com.lee.ssm.domain.UserInfo;
import com.lee.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
  private  IUserDao iUserDao;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo;
        userInfo = iUserDao.findByUsername(s);
        User user=new User(userInfo.getUsername(),userInfo.getPassword(),userInfo.getStatus()==0? false:true,true,true,true,getAuthority(userInfo.getRoles()));
    return user;
    }
    public List<SimpleGrantedAuthority>  getAuthority(List<Role> roles){
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));

        }
        return list;
    }

    @Override
    public List<UserInfo> findAll() throws Exception {
        return iUserDao.findAll();
    }

    @Override
    public UserInfo findById(String id) throws Exception {
        return iUserDao.findById(id);
    }

    @Override
    public void save(UserInfo userInfo) throws Exception {
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        iUserDao.save(userInfo);
    }

    @Override
    public void addRoleToUser(String userId, String[] ids) throws Exception {
        for (int i = 0; i < ids.length; i++) {
            iUserDao.addRoleToUser(userId,ids[i]);
        }
    }
}
